package com.coderfans.jedistest;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.coderfans.serializetest.Person;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;

/**
 * Created by 58 on 2016-8-8.
 */
public class JedisTest1 {
    //redis服务器的ip
    private static String JEDIS_HOST = "";

    //Redis的端口号
    private static int PORT = 6379;

    //可用连接实例的最大数目，默认值为8；
    //如果赋值为-1，则表示不限制；
    // 如果pool已经分配了maxActive个jedis实例，
    // 则此时pool的状态为exhausted(耗尽)。
    private static int MAX_ACTIVE = 1024;


    //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例，默认值也是8。
    private static int MAX_IDLE = 200;

    //等待可用连接的最大时间，单位毫秒，默认值为-1，表示永不超时，如果
    //超出等待时间则抛出JedisConnectionException
    private static int MAX_WAIT = 10000;

    private static int TIMEOUT = 10000;

    //在borrow一个jedis实例时，是否提前进行validate操作，如果为true,则得到的jedis实例均是可用的
    private static boolean TEST_ON_BORROW = true;

    /**
     * 声明单机版本的redis连接池
     */
    private static JedisPool jedisPool = null;
    private static ShardedJedisPool shardedJedisPool = null;

    /**
     * 生成jedis池
     */
    static {
        try {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxIdle(MAX_IDLE);
            config.setMaxWaitMillis(MAX_WAIT);
            config.setTestOnBorrow(TEST_ON_BORROW);
            jedisPool = new JedisPool(config,JEDIS_HOST,PORT,TIMEOUT);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 获取jedis实例
     * @return
     */
    public synchronized static Jedis getJedis(){
        try {
            if(jedisPool!=null){
                Jedis resource = jedisPool.getResource();
                return resource;
            }
            return null;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 生成shardedJedis池
     * @param serverInfo
     * @return
     */
    public synchronized  ShardedJedisPool getShardedJedisPool(String serverInfo){
        if(shardedJedisPool != null){
            return shardedJedisPool;
        }else {
            List<JedisShardInfo> jedisShardInfoList = new ArrayList<>();
            String [] serverArray = serverInfo.split(",");
            for (int i = 0 ;i < serverArray.length;i++ ){
                String[] serverBasic = serverArray[i].split(":");
                String host = serverBasic[0];
                int port = Integer.parseInt(serverBasic[1]);
                JedisShardInfo jedisShardInfo = new JedisShardInfo(host,port);
            }
            ShardedJedisPool shardedJedisPool = new ShardedJedisPool(new GenericObjectPoolConfig(),jedisShardInfoList);
            return shardedJedisPool;
        }
    }

    public GenericObjectPoolConfig getPoolConfig(){
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        return poolConfig;
    }


    @Deprecated
    //该方法已经过时在3.0的时候应该使用jedis.close()关闭
    public static void returnResource(final Jedis jedis){
        if(jedis != null){
            jedisPool.returnResource(jedis);
        }
    }


    public static void main(String[] args) {
        Jedis jedis = getJedis();
        String result = jedis.ping();
        /*System.out.println("result = "+result);
        String value =jedis.get("name");
        System.out.println("value = "+value);*/

        //set
        //long num = jedis.sadd("TestStr","1234567890");
        //在集合名称为TestStr的集合中添加一个元素
       /* long num1 = jedis.sadd("TestStr","1234567892");
        long num2 = jedis.sadd("TestStr","1234567890");
        long num0 = jedis.sadd("TestStr","1234567891");*/
        //System.out.println("num = "+num);
        //获取集合TestStr的大小
      /*  long nums = jedis.scard("TestStr");
        System.out.println("nums = "+nums);
        //获取所有集合的元素
        Set<String> stringSet = jedis.smembers("TestStr");
        stringSet.stream().forEach(System.out::println);*/


        Person person = new Person();
        person.setName("张三");
        person.setPassword("123456");
        person.setId((long)10001);
        long r = jedis.lpush("user", JSON.toJSONString(person));
        System.out.println("r = "+r);
        /*System.out.println(jedis.lpop("user"));*/

        /*Person person1 =  (Person) JSON.parse(jedis.lpop("user"));
        System.out.println(person1.toString());*/

    }


    public static JedisPool getJedisPool(final String ip,final String port){
        String url = ip+":"+port;
        return null;
    }

}
